<template>
  <div>
    <el-form @submit.native.prevent :inline="true" :model="params">
      <el-form-item>
        <select-address
          v-model="params.address_code"
          placeholder="地址查询"
          :auto-top="1"
          clearable
          :bottom-level="2"
          @change="getData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          placeholder="项目名称查询"
          clearable
          @keyup.enter.native="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <c-select
          v-model="loanBehStatusSelected"
          placeholder="项目状态选择"
          clearable
          number-key
          :options="{ 0: '在保项目', 1: '解保项目' }"
          @change="handleStatusChange"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <select-org-bank
          v-model="bankId"
          placeholder="选择银行"
          filterable
          clearable
          @select="selectBank"
        ></select-org-bank>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          class="date-picker-ml"
          v-model="datePicked"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="放款开始日期"
          end-placeholder="放款结束日期"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd"
          @change="handleDateChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-plus" @click="addCompensatory()">添加代偿</el-button>
      </el-form-item>
      <el-form-item>
        <el-popover v-model="selectVisible" placement="bottom" trigger="click" width="400">
          <el-button icon="el-icon-download" :loading="exportLoading" slot="reference">
            下载
          </el-button>
          <div>
            <div class="dl-wrap mb-1">
              <div class="dl-dt mt-1 text-right pr-2">选择担保年份</div>
              <div class="dl-dd">
                <el-date-picker
                  v-model="selectYear"
                  :clearable="false"
                  placeholder="选择年份"
                  :picker-options="pickerYear"
                  type="year"
                  value-format="yyyy"
                ></el-date-picker>
              </div>
            </div>
            <div class="dl-wrap mb-1">
              <div class="dl-dt"></div>
              <div class="dl-dd">
                <el-button
                  icon="el-icon-download"
                  type="primary"
                  :loading="exportLoading"
                  @click="exportExcel(innterTitle)"
                >
                  下载
                </el-button>
              </div>
            </div>
          </div>
        </el-popover>
      </el-form-item>
    </el-form>

    <!-- <h4 class="text-center font-weight-bold">{{innterTitle}}</h4> -->

    <c-table
      v-loading="loading"
      border
      header-row-class-name="mutiple-table-header"
      :columns="tableColumns"
      :data="tableData"
    >
      <template v-slot:warranty_method="scope">
        <div class="text-truncate" :title="scope.row.warranty_method">
          {{ scope.row.warranty_method }}
        </div>
      </template>
    </c-table>
    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <import-excel
      :title="importTitle"
      :visible.sync="importVisible"
      :post-api="importUrl"
      :excel-template="importTemplate"
      @success="getData(params.index)"
    ></import-excel>

    <!-- 添加代偿 -->
    <compensatory-add-dialog
      :visible.sync="compensatoryAddVisible"
      @success="getData()"
    ></compensatory-add-dialog>

    <!-- 登记代偿 -->
    <compensatory-edit-dialog
      :visible.sync="compensatoryEditVisible"
      :query-id="compensatoryEditRow.customer_related_id"
      @success="getData()"
    ></compensatory-edit-dialog>

    <!-- 登记追偿 -->
    <recovery-edit-dialog
      :visible.sync="recoveryEditVisible"
      :query-id="recoveryEditRow.customer_related_id"
      @success="getData()"
    ></recovery-edit-dialog>

    <!-- 查看 -->
    <ledger-view-dialog
      :visible.sync="viewVisible"
      :query-id="viewRow.customer_related_id"
      @success="getData()"
    ></ledger-view-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { lastPickerShortcuts, nextPickerShortcuts } from '@/common/plugins/tools/date'
import { exportExcel } from '@/credit/mixin/taskTableProvinceUnion'
import {
  enumPovertyProject,
  enumBuyInsurance,
  enumRiskType,
  enumCountryRiskType,
} from '@/credit/views/city/report/reportMixins'
import { queryTrouble } from '@vimi/utils-api'
import { enumISNom } from '@/gov/plugins/enum'
import { enumOrgClass } from '@/credit/plugins/enum'
import { dateFormat } from '@/common/utils/common'

import SelectOrgBank from '@/credit/components/select/SelectOrgBank'
import ImportExcel from '@/components/ImportExcel'
import SelectAddress from '@/components/select/SelectAddress'
import CompensatoryAddDialog from '@/credit/views/city/reportCity/ledger/component/CompensatoryAddDialog'
import CompensatoryEditDialog from '@/credit/views/city/reportCity/ledger/component/CompensatoryEditDialog'
import RecoveryEditDialog from '@/credit/views/city/reportCity/ledger/component/RecoveryEditDialog'
import ledgerViewDialog from '@/credit/views/city/reportCity/ledger/component/LedgerViewDialog'
import { sub } from '@vimi/utils-tool'

export default {
  components: {
    SelectOrgBank,
    ImportExcel,
    SelectAddress,
    CompensatoryAddDialog,
    CompensatoryEditDialog,
    RecoveryEditDialog,
    ledgerViewDialog,
  },
  props: {},
  data() {
    return {
      enumISNom,
      loading: false,
      params: {
        index: 1,
        size: 10,
        load_beh_status: '',
        'orWhere.service_id.eq': '',
        'orWhere.pro_service.eq': '',
        'bank_id.eq': '',
        'is_compens.eq': 1,
      },
      order: { load_date: 'desc' },
      tableName: 'market_project',
      totalCount: 0,
      tableData: [],
      tableColumns: [
        { attrs: { label: '序号', prop: 'index', align: 'center', minWidth: 50, fixed: 'left' } },
        {
          attrs: {
            label: '借款人/担保客户',
            prop: 'customer_name',
            align: 'center',
            minWidth: 200,
            fixed: 'left',
          },
        },
        { attrs: { label: '贷款银行', prop: 'bank_name', align: 'center', minWidth: 160 } },
        { attrs: { label: '客户类型', prop: 'org_class_name', align: 'center', minWidth: 160 } },
        {
          attrs: { label: '十二大产业分类', prop: 'main_business', align: 'center', minWidth: 160 },
          process: v => v || '-',
        },
        {
          attrs: { label: '导入日期', prop: 'create_time', align: 'center', minWidth: 120 },
          process: v => this.$utils.dateFormat(v, 'yyyy-MM-dd'),
        },
        {
          attrs: {
            label: '贷款金额/拟担保金额(万元)',
            prop: 'warranty_amount',
            align: 'center',
            minWidth: 140,
          },
        },
        {
          attrs: { label: '代偿金额(元)', prop: 'compens_funds', align: 'center', minWidth: 140 },
        },
        {
          attrs: {
            label: '追偿金额(元)',
            prop: 'recovery_funds',
            align: 'center',
            minWidth: 140,
          },
        },
        {
          attrs: { label: '代偿剩余金额(元)', prop: 'leftFunds', align: 'center', minWidth: 140 },
        },
        {
          attrs: { label: '放款日/拟担保起始日', prop: 'loadDate', align: 'center', minWidth: 140 },
        },
        { attrs: { label: '到期日', prop: 'loadEndDate', align: 'center', minWidth: 100 } },
        {
          attrs: { label: '贷款期限(月)', prop: 'warranty_period', align: 'center', minWidth: 120 },
        },
        { attrs: { label: '贷款利率(年)', prop: 'load_rate', align: 'center', minWidth: 120 } },
        {
          attrs: { label: '行业分类', prop: 'industrial_name', align: 'center', minWidth: 170 },
          process: v => v || '-',
        },
        {
          attrs: {
            label: '主营业务',
            prop: 'parent_main_business',
            align: 'center',
            minWidth: 170,
          },
          process: v => v || '-',
        },
        {
          attrs: {
            label: '反担保措施(详情)',
            prop: 'warranty_method',
            align: 'center',
            minWidth: 160,
          },
          slot: 'warranty_method',
        },
        { attrs: { label: '销售收入(万元)', prop: 'sale_income', align: 'center', minWidth: 120 } },
        {
          attrs: { label: '资产总额(万元)', prop: 'assets_total', align: 'center', minWidth: 120 },
        },
        {
          attrs: {
            label: '委托担保合同编号',
            prop: 'ensure_contract',
            align: 'center',
            minWidth: 160,
          },
        },
        { attrs: { label: '保证合同编号', prop: 'gua_contract', align: 'center', minWidth: 160 } },
        {
          attrs: {
            label: '是否购买农业保险',
            prop: 'isBuyInsurance',
            align: 'center',
            minWidth: 140,
          },
        },
        { attrs: { label: '贷款用途', prop: 'funds_use_dir', align: 'center', minWidth: 140 } },
        {
          attrs: {
            label: '是否为扶贫项目',
            prop: 'isPovertyProject',
            align: 'center',
            minWidth: 140,
          },
        },
        {
          attrs: { label: '征信逾期情况', align: 'center' },
          columns: [
            {
              attrs: { label: '逾期次数', prop: 'overdue_count', align: 'center', minWidth: 140 },
              process: v => v || '-',
            },
            {
              attrs: {
                label: '逾期合计金额',
                prop: 'overdue_funds',
                align: 'center',
                minWidth: 140,
              },
              process: v => v || '-',
            },
          ],
        },
        { attrs: { label: '分险比例(%)', prop: 'risk_rate', align: 'center', minWidth: 120 } },
        { attrs: { label: '实际控制人', prop: 'corp_name', align: 'center', minWidth: 120 } },
        { attrs: { label: '联系电话', prop: 'corp_phone', align: 'center', minWidth: 140 } },
        {
          attrs: {
            label: '客户身份证号码/统一社会信用代码',
            prop: 'lender_idcard',
            align: 'center',
            minWidth: 140,
          },
          process: v => v || '-',
        },
        { attrs: { label: '客户住址/经营地址', prop: 'address', align: 'center', minWidth: 140 } },
        { attrs: { label: '担保机构', prop: 'service_name', align: 'center', minWidth: 140 } },
        {
          attrs: {
            label: '项目状态(在保/解保)',
            prop: 'loanBehStatus',
            align: 'center',
            minWidth: 120,
          },
        },
        { attrs: { label: '备注', prop: 'remark', align: 'center', minWidth: 140 } },
        {
          attrs: { label: '操作', align: 'center', width: 150, fixed: 'right' },
          operations: [
            {
              content: '登记代偿',
              icon: 'fa fa-gavel',
              event: this.handleComp,
            },
            {
              content: '登记追偿',
              icon: 'fa fa-credit-card',
              event: this.handerRecovery,
            },
            {
              content: '查看',
              icon: 'fa fa-search',
              event: this.handlerView,
            },
            {
              content: '删除',
              icon: 'fa fa-trash',
              event: this.handlerDelete,
            },
          ],
        },
      ],

      importUrl: '',
      importKey: '',
      importTitle: '导入十二贷项目台账',
      importTemplate: '',
      importVisible: false,

      exportLoading: false,

      loanBehStatusSelected: '',
      datePicked: [],
      pickerOptions: {
        shortcuts: [...lastPickerShortcuts, ...nextPickerShortcuts],
      },
      selectVisible: false,
      selectYear: '',
      bankId: '',

      // 添加代偿
      compensatoryAddVisible: false,
      // 登记代偿
      compensatoryEditVisible: false,
      compensatoryEditRow: {},
      // 登记追偿
      recoveryEditVisible: false,
      recoveryEditRow: {},
      // 查看
      viewVisible: false,
      viewRow: {},
    }
  },
  computed: {
    ...mapGetters(['org', 'clientId']),
    innterTitle() {
      return `${this.org.orgName} 代偿项目统计表-${new Date(this.selectYear).getFullYear()}年`
    },
    pickerYear() {
      return {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
      }
    },
  },
  watch: {},
  created() {
    this.selectYear = new Date()
    this.importUrl =
      '/api/credit/import/' +
      queryTrouble('datum_one_county_industry', {
        importKey: this.importKey,
        'service_id.eq': this.clientId,
      })

    this.params['orWhere.service_id.eq'] = this.clientId
    this.params['orWhere.recommend_service.eq'] = this.clientId
    this.getData()
  },
  mounted() {},
  methods: {
    handlerDelete(row) {
      this.$utils
        .msgbox({
          message: `确定删除${row.customer_name}代偿以及追偿信息?`,
          beforeClose: () =>
            this.$api.updateData(this.$serviceName, 'market_project', row.customer_related_id, {
              is_compens: 0,
              compens_funds: 0,
              recovery_funds: 0,
            }),
        })
        .then(() => {
          this.getData()
          this.$message.success('删除成功！')
        })
        .catch(() => this.$message.error('删除失败，请重试！'))
    },
    getCount() {
      const { index, size, ...params } = { ...this.params }
      params.groupFunc = 'round(sum(compens_funds)|2),round(sum(recovery_funds)|2)'
      this.$api.getData(this.$serviceName, this.tableName, params).then(res => {
        const data = (res && res.data && res.data[0]) || {}
        const compensIndex = this.tableColumns.findIndex(col => col.attrs.prop === 'compens_funds')
        const recoveryIndex = this.tableColumns.findIndex(
          col => col.attrs.prop === 'recovery_funds'
        )
        const leftFundsIndex = this.tableColumns.findIndex(col => col.attrs.prop === 'leftFunds')
        this.tableColumns[compensIndex].attrs.label = `代偿金额(${data.p || '-'}元)`
        this.tableColumns[recoveryIndex].attrs.label = `追偿金额(${data.p1 || '-'}元)`
        this.tableColumns[leftFundsIndex].attrs.label = `代偿剩余金额(${
          sub(data.p, data.p1) || '-'
        }元)`
      })
    },
    reportDataAdapter(item, index) {
      item.index = index + 1
      item.customerTypeName = enumOrgClass[item.org_class] || '-'
      item.isPovertyProject = enumPovertyProject[item.is_poverty_project] || '-'
      item.isDualControl = enumBuyInsurance[item.is_dual_control] || '-'
      item.loanBehStatus = +item.load_beh_status === 6 ? '解保' : '在保'
      item.isBuyInsurance = enumBuyInsurance[item.is_buy_insurance] || '-'

      item.risk_type = +item.risk_type || null
      item.risk_type_name = enumRiskType[item.risk_type] || '-'
      item.riskTye = enumCountryRiskType[item.risk_tye] || '-'
      item.loadDate = dateFormat(item.load_date, 'yyyy-MM-dd')
      item.loadEndDate = dateFormat(item.load_end_date, 'yyyy-MM-dd')
      item.isBatch = +item.gua_type === 3 ? '是' : '否'
      item.leftFunds = sub(item.compens_funds, item.recovery_funds)
      return item
    },
    selectBank(bank) {
      this.params['bank_code.endlike'] = bank.agency_code
      this.getData()
    },
    async getData(index = 1) {
      this.params.index = index
      this.getCount()
      this.loading = true
      const [res] = await this.fetchData(this.params)
      this.loading = false
      const data = (res && res.data) || {}
      this.totalCount = data.totalCount || 0
      this.tableData = (data.data || []).map(this.reportDataAdapter)
    },
    fetchData(params) {
      return this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, params, this.order)
      )
    },
    handleDateChange() {
      this.params.index = 1
      if (this.datePicked && this.datePicked.length === 2) {
        this.params['load_date.gte'] = this.datePicked[0]
        this.params['load_date.lte'] = `${this.datePicked[1]} 23:59:59`
      } else {
        this.params['load_date.gte'] = ''
        this.params['load_date.lte'] = ''
      }
      this.getData()
    },
    handleStatusChange() {
      switch (this.loanBehStatusSelected) {
        case 0:
          this.params['load_beh_status.neq'] = 6
          this.params['load_beh_status.eq'] = ''
          break
        case 1:
          this.params['load_beh_status.neq'] = ''
          this.params['load_beh_status.eq'] = 6
          break
        default:
          this.params['load_beh_status.neq'] = ''
          this.params['load_beh_status.eq'] = ''
          break
      }
      this.getData()
    },
    async exportExcel(filename) {
      let params = {}
      if (this.selectYear) {
        params = {
          'load_date.gte': this.$utils.dateFormat(this.selectYear, 'yyyy-MM-dd'),
          'load_date.lt': `${new Date(this.selectYear).getFullYear() + 1}-01-01`,
        }
      }
      this.exportLoading = true
      exportExcel({
        filename,
        tableColumns: this.tableColumns,
        params: { ...this.params, ...params },
        dataAdapter: this.reportDataAdapter,
        fetchData: this.fetchData,
        onLoaded: () => {
          this.exportLoading = false
          this.selectVisible = false
        },
      })
    },

    // 添加代偿
    addCompensatory() {
      this.compensatoryAddVisible = true
    },

    // 登记代偿
    handleComp(row) {
      this.compensatoryEditRow = row
      this.compensatoryEditVisible = true
    },

    // 登记追偿
    handerRecovery(row) {
      this.recoveryEditRow = row
      this.recoveryEditVisible = true
    },

    // 查看
    handlerView(row) {
      this.viewRow = row
      this.viewVisible = true
    },
  },
}
</script>

<style lang="scss" scoped></style>
